<template>
  <div>
    <Header :left="true" leftText="返回" title="未完成任务" />
    <div>
      <DropdownMenu style="margin-top:10px;background-color:#D3D3D3">
        <DropdownItem v-model="siteIndex" :options="sites" @change="siteChange" />
        <DropdownItem v-model="departIndex" :options="departments" @change="departChange" />
        <DropdownItem v-model="taskTypeIndex" :options="taskTypes" @change="taskTypeChange" />
        <DropdownItem ref="time" title="时间" @open="showDialog = true" />
      </DropdownMenu>
    </div>
    <van-dialog
      v-model="showDialog"
      title="查询条件选择"
      show-cancel-button
      confirm-button-text="确认"
      cancel-button-text="取消"
      @confirm="timeConfirm"
      @cancel="clearTime"
    >
      <Form :style="autoHeight">
        <van-field
          readonly
          clickable
          name="timeStr"
          v-model="valueStrTime"
          label="开始时间"
          placeholder="点击选择日期"
          @click="openStartTime"
        />
        <!-- <van-calendar
          v-model="showCalendarStr"
          @confirm="onConfirmStr"
          @closed="startConcel"
          :min-date="minDate"
          :max-date="maxDate"
        /> -->
        <van-field
          readonly
          clickable
          name="timeEnd"
          :value="valueEndTime"
          label="结束时间"
          placeholder="点击选择日期"
          @click="openEndTime"
        />
        <div v-show="showCalendarStr">
          <!-- <van-popup v-model="showCalendarStr" round position="bottom"> -->
          <van-datetime-picker
            v-model="valueStr"
            type="datetime"
            title="选择时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmStr"
            @cancel="startConcel"
          />
          <!-- </van-popup> -->
        </div>
        <div v-show="showCalendarEnd">
          <!-- <van-popup v-model="showCalendarEnd" round position="bottom"> -->
          <van-datetime-picker
            v-model="valueEnd"
            type="datetime"
            title="选择时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmEnd"
            @cancel="endConcel"
          />
          <!-- </van-popup> -->
        </div>
        <!-- <van-calendar
          v-model="showCalendarEnd"
          @confirm="onConfirmEnd"
          @closed="endConcel"
          :min-date="minDate"
          :max-date="maxDate"
        /> -->
      </Form>
    </van-dialog>
    <!-- 统计图 -->
    <!-- 条形图 -->
    <div>
      <canvas id="mountNode" style="width:100%;height:250px;"></canvas>
    </div>
    <van-divider>表格统计</van-divider>
    <div class="selectdTextScroll">
      <v-table
        is-horizontal-resize
        style="width:100%;"
        :show-vertical-border="true"
        :columns="columns"
        :table-data="tableData"
        :row-click="rowClick"
        row-hover-color="#eee"
        row-click-color="#edf7ff"
      ></v-table>
    </div>
  </div>
</template>
<script>
import {
  Icon,
  DropdownMenu,
  DropdownItem,
  Button,
  CellGroup,
  Cell,
  Field,
  Col,
  Row,
  Image as VanImage,
  Checkbox,
  Pagination,
  Search,
  Sticky,
  Toast,
  Dialog,
  Divider,
  Calendar,
  DatetimePicker,
} from 'vant'
Vue.use(Divider)
Vue.use(Calendar)
Vue.use(DatetimePicker)
Vue.use(Field)
Vue.use(Dialog)
import { _httpClient } from '@/libs/api'
import F2 from '@antv/f2/lib/index-all'
import Header from '@/components/header.vue'
import { VTable } from 'vue-easytable'
import 'vue-easytable/libs/themes-base/index.css'
import { storage } from '@/libs/utils'
import { removeToken, getToken, setBaseApiFrefix, getBaseApiFrefix } from '@/libs/auth'
export default {
  components: {
    Button,
    Header,
    Icon,
    CellGroup,
    Cell,
    Field,
    Col,
    Row,
    Search,
    Sticky,
    DropdownMenu,
    DropdownItem,
    Divider,
    VTable,
    Dialog,
  },

  data() {
    return {
      //查询条件
      siteIndex: 0, //工厂
      departIndex: 0, //部门
      taskTypeIndex: 0, //任务类型
      valueStr: null, //开始时间查询条件
      valueStrTime: null, //开始时间查询条件
      valueEnd: null, //结束时间查询条件
      valueEndTime: null, //结束时间查询条件

      user: [],
      dpIndex: 0,
      //弹窗高度
      autoHeight: {
        height: '',
      },
      showCalendarStr: false,
      showCalendarEnd: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2030, 11, 31),
      showDialog: false,
      info: {
        user: null,
        type: '',
        siteKey: null,
        department: null,
        taskType: null,
      },
      type: '',
      tableData: [
        { seq: '1', department: '质量部', dayTask: '30', weekTask: '20', monthTask: '40', techTask: '50' },
        { seq: '1', department: '工艺部', dayTask: '30', weekTask: '20', monthTask: '40', techTask: '50' },
        { seq: '1', department: '生产部', dayTask: '30', weekTask: '20', monthTask: '40', techTask: '50' },
      ],
      pointColumns: [
        //点检表格列头
        {
          field: 'seqNum',
          title: '序号',
          width: 40,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'department',
          title: '部门',
          width: 100,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'dayTaskNum',
          title: '日任务',
          width: 65,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'weekTaskNum',
          title: '周任务',
          width: 65,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'monthTaskNum',
          title: '月任务',
          width: 65,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'techTaskNum',
          title: '工艺点检',
          width: 75,
          titleAlign: 'center',
          columnAlign: 'center',
          titleCellClassName: 'title-cell-class-name-test',
          isResize: true,
        },
      ],
      repairColumns: [
        //维修表格列头
        {
          field: 'seqNum',
          title: '序号',
          width: 40,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'department',
          title: '部门',
          width: 60,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'taskNum',
          title: '维修',
          width: 65,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
      ],
      columns: [],
      sites: [], //工厂
      departments: [], //部门
      taskTypes: [
        { value: 0, text: '点检' },
        { value: 1, text: '维修' },
      ], //任务类型
      data1: [], //饼图数据
      data: [],
    }
  },
  created: function() {
    let oldHight = api.winWidth
    this.screenWidth = oldHight
    //获取当前系统登录用户
    this.user = JSON.parse(storage.get('user'))
    //初始化设置弹窗高度
    this.autoHeight.height = '100px'
    //表格列头初始化
    this.columns = this.pointColumns

    this.minDate = new Date(new Date().getFullYear() - 3, 0, 1)
    this.maxDate = new Date(new Date().getFullYear() + 3, 0, 1)

    //默认查询时间
    this.valueStrTime = this.formatDateStart(new Date())

    this.valueEndTime = this.formatDateEnd(new Date())

    //初始化查询条件
    this.initQuertSiteList()
    // this.initQuertDepartList()
  },
  mounted: function() {
    //数据查询
    // this.queryPointCheckData()
  },

  methods: {
    //表格点击监听
    rowClick(rowIndex, columnName, rowData) {
      if (rowData.title == '部门' || rowData.title == '序号') {
        return
      }
      if (this.taskTypeIndex == 1) {
        api.openWin({
          name: 'repairRecordList',
          url: './report-repairRecordList.html',
          type: 'fade',
          pageParam: {
            siteKey: this.siteIndex,
            department: this.tableData[rowIndex].department,
            startTime: this.valueStrTime,
            endTime: this.valueEndTime,
            type: 1,
          },
        })
      } else {
        api.openWin({
          name: 'taskFinishList',
          url: './report-taskNoFinishList.html',
          type: 'fade',
          pageParam: {
            siteKey: this.siteIndex,
            department: this.tableData[rowIndex].department,
            taskType: rowData.title,
            valueStrTime: this.valueStrTime,
            valueEndTime: this.valueEndTime,
            type: 1,
          },
        })
      }
    },
    //时间确认查询
    timeConfirm() {
      if (this.taskTypeIndex == 0) {
        //重新查询数据
        this.queryPointCheckData()
      } else {
        //重新查询数据
        this.quertRepairInfoList()
      }
    },
    //查询点检任务数据
    queryPointCheckData() {
      this.quertPointCheckList()
      this.quertPointCheckTableList()
    },
    //下拉框工厂数据切换
    siteChange(value) {
      this.siteIndex = value
      this.initQuertDepartList(value)
      if (this.taskTypeIndex == 0) {
        //重新查询数据
        this.queryPointCheckData()
      } else {
        //重新查询数据
        this.quertRepairInfoList()
      }
    },
    //部门数据切换
    departChange(value) {
      this.departIndex = value
      if (this.taskTypeIndex == 0) {
        //重新查询数据
        this.queryPointCheckData()
      } else {
        //重新查询数据
        this.quertRepairInfoList()
      }
    },
    //任务类型数据切换
    taskTypeChange(value) {
      this.taskTypeIndex = value
      if (value == 0) {
        this.queryPointCheckData()
        this.columns = this.pointColumns
      } else if (value == 1) {
        this.quertRepairInfoList()
        this.columns = this.repairColumns
      }
    },

    //初始化查询工厂下拉框
    async initQuertSiteList() {
      let _this = this
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/report/siteList')
        if (res.code === 200) {
          if (res.rows.length > 0) {
            _this.sites = []
            res.rows.forEach(function(item, index) {
              let site = { value: item.siteKey, text: item.siteName }
              _this.sites.push(site)
            })
            _this.siteIndex = _this.sites[0].value
            _this.initQuertDepartList(_this.siteIndex)
            _this.queryPointCheckData()
          }
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //初始化查询部门下拉框
    async initQuertDepartList(val) {
      let _this = this
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/system/dept/applist', {
          body: { parentId: val },
        })
        if (res.code === 200) {
          if (res.data.length > 0) {
            _this.departments = []
            let depart = { value: 0, text: '所有部门' }
            _this.departments.push(depart)
            for (let i = 0; i < res.data.length; i++) {
              let newDepart = { value: i + 1, text: res.data[i].deptName }
              _this.departments.push(newDepart)
            }
            _this.departIndex = _this.departments[0].value
          }
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //查询点检图表数据
    async quertPointCheckList() {
      let _this = this
      //部门
      let department
      if (_this.departments.length != 0 && _this.departments[_this.departIndex].value != 0) {
        department = _this.departments[_this.departIndex].text
      }
      //工厂
      let site
      if (_this.sites.length != 0) {
        site = _this.siteIndex
      }
      _this.type = 1
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/report/list', {
          body: {
            siteKey: site,
            department: department,
            startTime: _this.valueStrTime,
            endTime: _this.valueEndTime,
            type: 1,
          },
        })
        if (res.code === 200) {
          _this.data = res.rows
          //调用方法绘制柱形图
          _this.drawChart()
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //查询点检表格数据
    async quertPointCheckTableList() {
      let _this = this
      //部门
      let department
      if (_this.departments.length != 0 && _this.departments[_this.departIndex].value != 0) {
        department = _this.departments[_this.departIndex].text
      }
      //工厂
      let site
      if (_this.sites.length != 0) {
        site = _this.siteIndex
      }
      _this.type = 1
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/report/tableList', {
          body: {
            siteKey: site,
            department: department,
            startTime: _this.valueStrTime,
            endTime: _this.valueEndTime,
            type: 1,
          },
        })
        if (res.code === 200) {
          _this.tableData = res.rows
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //查询维修任务信息
    async quertRepairInfoList() {
      let _this = this
      //部门
      let department
      if (_this.departments.length != 0 && _this.departments[_this.departIndex].value != 0) {
        department = _this.departments[_this.departIndex].text
      }
      //工厂
      let site
      if (_this.sites.length != 0) {
        site = _this.siteIndex
      }
      _this.type = 1
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/report/repairList', {
          body: {
            siteKey: site,
            department: department,
            startTime: _this.valueStrTime,
            endTime: _this.valueEndTime,
            type: 1,
          },
        })
        if (res.code === 200) {
          _this.data = res.rows
          _this.tableData = res.rows
          //调用方法绘制柱形图
          _this.drawChart()
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //日期格式化
    formatDateStart(date) {
      let year = date.getFullYear()
      let mouth = date.getMonth() + 1
      if (mouth < 10) {
        mouth = '0' + mouth
      }
      let day = date.getDate()
      if (day < 10) {
        day = '0' + day
      }
      let currentDate = new Date()
      let currentShifDate = new Date()
      currentShifDate.setHours(20)
      currentShifDate.setMinutes(30)
      currentShifDate.setSeconds(0)
      if (currentDate.getTime() >= currentShifDate.getTime()) {
        return year + '-' + mouth + '-' + day + ' ' + '20' + ':' + '30' + ':' + '00'
      }

      let currentDate2 = new Date()
      let currentShifDate2 = new Date()
      currentShifDate2.setHours(8)
      currentShifDate2.setMinutes(30)
      currentShifDate2.setSeconds(0)
      if (currentDate2.getTime() < currentShifDate2.getTime()) {
        if (date.getDate() == 1) {
          if (mouth == 1) {
            year = year - 1
          }
          mouth = mouth - 1
        }
        date.setDate(date.getDate() - 1)
        let day = date.getDate()
        if (day < 10) {
          day = '0' + day
        }
        return year + '-' + mouth + '-' + day + ' ' + '20' + ':' + '30' + ':' + '00'
      }

      return year + '-' + mouth + '-' + day + ' ' + '08' + ':' + '30' + ':' + '00'
    },

    //日期格式化
    formatDateEnd(date) {
      let currentDate = new Date()
      let currentShifDate = new Date()
      currentShifDate.setHours(20)
      currentShifDate.setMinutes(30)
      currentShifDate.setSeconds(0)
      if (currentDate.getTime() >= currentShifDate.getTime()) {
        date.setDate(date.getDate() + 1)
      }
      let year = date.getFullYear()
      let mouth = date.getMonth() + 1
      if (mouth < 10) {
        mouth = '0' + mouth
      }
      let day = date.getDate()
      if (day < 10) {
        day = '0' + day
      }

      if (currentDate.getTime() >= currentShifDate.getTime()) {
        return year + '-' + mouth + '-' + day + ' ' + '08' + ':' + '30' + ':' + '00'
      }

      let currentDate2 = new Date()
      let currentShifDate2 = new Date()
      currentShifDate2.setHours(8)
      currentShifDate2.setMinutes(30)
      currentShifDate2.setSeconds(0)
      if (currentDate2.getTime() < currentShifDate2.getTime()) {
        return year + '-' + mouth + '-' + day + ' ' + '08' + ':' + '30' + ':' + '00'
      }

      return year + '-' + mouth + '-' + day + ' ' + '20' + ':' + '30' + ':' + '00'
    },

    formatDate2(date) {
      let year = date.getFullYear()
      let mouth = date.getMonth() + 1
      let day = date.getDate()
      let hour = date.getHours()
      let min = date.getMinutes()
      if (mouth < 10) {
        mouth = '0' + mouth
      }
      if (day < 10) {
        day = '0' + day
      }
      if (hour < 10) {
        hour = '0' + hour
      }
      if (min < 10) {
        min = '0' + min
      }
      return year + '-' + mouth + '-' + day + ' ' + hour + ':' + min + ':' + '00'
    },

    //时间清空
    clearTime() {
      this.valueStrTime = null
      this.valueEndTime = null
      if (this.taskTypeIndex == 0) {
        //重新查询数据
        this.queryPointCheckData()
      } else {
        //重新查询数据
        this.quertRepairInfoList()
      }
    },

    //开始时间取消
    startConcel() {
      this.showCalendarStr = false
      this.autoHeight.height = '100px'
    },
    //结束时间取消
    endConcel() {
      // this.valueEnd = ''
      this.showCalendarEnd = false
      this.autoHeight.height = '100px'
    },

    //打开开始时间选择
    openStartTime() {
      this.showCalendarStr = true
      // this.valueStr = new Date(this.formatDate(new Date()))
      this.valueStr = new Date()
      let currentDate = new Date()
      let currentShifDate = new Date()
      currentShifDate.setHours(20)
      currentShifDate.setMinutes(30)
      currentShifDate.setSeconds(0)
      if (currentDate.getTime() >= currentShifDate.getTime()) {
        this.valueStr.setHours(20)
      } else {
        this.valueStr.setHours(8)
      }

      this.valueStr = new Date()
      let currentDate2 = new Date()
      let currentShifDate2 = new Date()
      currentShifDate2.setHours(8)
      currentShifDate2.setMinutes(30)
      currentShifDate2.setSeconds(0)
      if (currentDate2.getTime() < currentShifDate2.getTime()) {
        this.valueStr.setDate(currentDate2.getDate() - 1)
        this.valueStr.setHours(20)
      } else {
        this.valueStr.setHours(8)
      }

      this.valueStr.setMinutes(30)
      this.valueStr.setSeconds(0)


      this.autoHeight.height = '400px'
    },

    //打开结束时间选择
    openEndTime() {
      this.showCalendarEnd = true
      this.valueEnd = new Date()

      let currentDate = new Date()
      let currentShifDate = new Date()
      currentShifDate.setHours(20)
      currentShifDate.setMinutes(30)
      currentShifDate.setSeconds(0)
      if (currentDate.getTime() >= currentShifDate.getTime()) {
        this.valueEnd.setDate(currentDate.getDate() + 1)
        this.valueEnd.setHours(8)
      } else {
        this.valueEnd.setHours(20)
      }

      this.valueEnd = new Date()
      let currentDate2 = new Date()
      let currentShifDate2 = new Date()
      currentShifDate2.setHours(8)
      currentShifDate2.setMinutes(30)
      currentShifDate2.setSeconds(0)
      if (currentDate2.getTime() < currentShifDate2.getTime()) {
        this.valueEnd.setHours(8)
      } else {
        this.valueEnd.setHours(20)
      }

      this.valueEnd.setMinutes(30)
      this.valueEnd.setSeconds(0)
      this.autoHeight.height = '400px'
    },

    //开始时间确定
    onConfirmStr(date) {
      this.valueStr = this.formatDate2(date)
      this.valueStrTime = this.valueStr
      this.showCalendarStr = false
      this.autoHeight.height = '100px'
    },
    //结束时间确认
    onConfirmEnd(date) {
      this.valueEnd = this.formatDate2(date)
      this.valueEndTime = this.valueEnd
      this.showCalendarEnd = false
      this.autoHeight.height = '100px'
    },
    //绘制柱状图
    drawChart() {
      var Shape = F2.Shape
      var Util = F2.Util
      Shape.registerShape('interval', 'text', {
        draw: function draw(cfg, container) {
          var points = this.parsePoints(cfg.points)
          var style = Util.mix(
            {
              fill: cfg.color,
              z: true, // 需要闭合
            },
            cfg.style
          )
          var intervalShape = container.addShape('rect', {
            attrs: Util.mix(
              {
                x: points[1].x,
                y: points[1].y,
                width: points[2].x - points[1].x,
                height: points[0].y - points[1].y,
              },
              style
            ),
          })

          var origin = cfg.origin._origin // 获取对应的原始数据记录
          var textShape = container.addShape('text', {
            zIndex: 1,
            attrs: {
              x: (points[1].x + points[2].x) / 2,
              y: points[1].y - 5, // 往上偏移 5 像素
              text: origin['taskNum'],
              fill: '#808080',
              textAlign: 'center',
              textBaseline: 'bottom',
              fontSize: 10, // 字体大小
            },
          })
          container.sort()
          return [intervalShape, textShape]
        },
      })

      var chart = new F2.Chart({
        id: 'mountNode',
        pixelRatio: window.devicePixelRatio,
      })
      chart.source(this.data)
      chart.legend(true)
      chart.legend({
        align: 'center',
        itemWidth: null, // 图例项按照实际宽度渲染
      })
      chart.tooltip({
        showItemMarker: false,
        onShow: function onShow(ev) {
          var item = ev.items
          if (this.taskTypeIndex == 1) {
            api.openWin({
              name: 'repairRecordList',
              url: './report-repairRecordList.html',
              type: 'fade',
              pageParam: {
                siteKey: this.siteIndex,
                department: this.tableData[rowIndex].department,
                taskType: rowData.title,
                valueStrTime: this.valueStrTime,
                valueEndTime: this.valueEndTime,
                type: 1,
              },
            })
          } else {
            api.openWin({
              name: 'taskNoFinishList',
              url: './report-taskNoFinishList.html',
              type: 'fade',
              pageParam: {
                siteKey: this.siteIndex,
                department: item[0].origin.department,
                taskType: item[0].origin.taskType,
                valueStrTime: this.valueStrTime,
                valueEndTime: this.valueEndTime,
                type: 1,
              },
            })
          }
        },
      })
      chart
        .interval()
        .position('department*taskNum')
        .color('taskType')
        .shape('text')
        .adjust({
          type: 'dodge',
          marginRatio: 0.2,
        })
        .style({
          radius: [4, 4, 0, 0],
        })

      chart.render()
    },
  },
}
</script>
<style>
body {
  background-color: White;
}
.selectdTextScroll {
  display: inline-block;
  /* position: fixed; */
  top: 9rem;
  overflow: scroll;
  right: 0;
  width: 100%;
  height: 240px;
  z-index: 1;
}
.title-cell-class-name-test {
  background-color: #778899;
  color: #fff;
}
</style>
